package com.hw.ui.relation_scanf;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.hw.HWApp;
import com.hw.base.model.BaseModel;
import com.hw.base.util.Util;
import com.hw.bean.AbBean;
import com.hw.bean.AbScanfBean;
import com.hw.daobean.DataBaseControl;
import com.hw.daobean.ProductInfo;
import com.hw.daobean.RelationInfo;
import com.hw.daobean.RelationUpInfo;
import com.hw.tool.VoiceUtils;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;
import okhttp3.Response;

public class RelationScanfModelImpl extends BaseModel implements RelationScanfModel {
    private String tag = "RelationScanfModelImpl";
    private String msg = "";
    AbBean abBean;
    AbScanfBean bean;
    List<String> boxcodes;
    String casecode;

    public RelationScanfModelImpl(Context context) {
        super(context);
        boxcodes = new ArrayList<String>();
        casecode = "";
    }

    public void postHandle(final CallBack callBack, final int n) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                switch (n) {
                    case -1:
                        VoiceUtils.voiceWarn(mContext);
                        callBack.onFail(msg);
                        break;
                    case 0:
                        callBack.onupdate(bean, msg);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    public void addBox(String string, AbScanfBean abScanfBean, final CallBack listener) {
        try {
            bean = abScanfBean;
            if (boxcodeJudge(string)) {
                msg = "盒码长度不符";
                postHandle(listener, -1);
                return;
            } else if (boxcodes.contains(string)) {
                msg = "盒码重复";
                postHandle(listener, -1);
                return;
            } else if (DataBaseControl.containBox(string)) {
                msg = "盒码重复";
                postHandle(listener, -1);
                return;
            } else if (DataBaseControl.containUpBox(string)) {
                msg = "盒码重复";
                postHandle(listener, -1);
                return;
            } else {
                boxcodes.add(string);
                bean.setBoxNum(boxcodes.size());
                bean.setBoxcodes(boxcodes);
                msg = "添加盒码成功";
                postHandle(listener, 0);
            }
        } catch (Exception e) {
            msg = "数据处理异常";
            postHandle(listener, -1);
        }
    }

    public void addCase(final String string, AbScanfBean abScanfBean, final CallBack listener) {
        bean = abScanfBean;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (casecodeJudge(string)) {
                        msg = "箱码长度不符";
                        postHandle(listener, -1);
                        return;
                    }
//                    else if (caseWl(string)) {
//                        msg = "箱码与产品不匹配";
//                        postHandle(listener, -1);
//                        return;
//                    }
                    else if (DataBaseControl.containCase(string)) {
                        msg = "箱码重复";
                        postHandle(listener, -1);
                        return;
                    } else if (DataBaseControl.containUpCase(string)) {
                        msg = "箱码重复";
                        postHandle(listener, -1);
                        return;
                    }
                    else {
                        casecode = string;
                        String res = commitCode(listener);
                        abBean = gson.fromJson(res, AbBean.class);
                        //上传成功
                        if (abBean.getErrcode() == 0) {
                            for (int i = 0; i < boxcodes.size(); i++) {
                                RelationInfo relationInfo = new RelationInfo(null, bean.getPid(), bean.getPname(), bean.getBatch(), casecode, boxcodes.get(i));
                                DataBaseControl.addRelation(relationInfo);
                            }
                            boxcodes.clear();
                            casecode = "";
                            msg = "添加箱码成功";
                            bean.setBoxcodes(boxcodes);
                            bean.setBoxNum(boxcodes.size());
                            int a = caseTotalNum(DataBaseControl.getlist(bean.getPid(), bean.getBatch()));
                            bean.setNum(a);
                            int b = caseUpTotalNum(DataBaseControl.getUplist(bean.getPid(), bean.getBatch()));
                            bean.setUpnum(b);
                            postHandle(listener, 0);
                        }
                        else {
//                            for (int i = 0; i < boxcodes.size(); i++) {
//                                RelationUpInfo relationUpInfo = new RelationUpInfo(null, bean.getPid(), bean.getPname(), bean.getBatch(), casecode, boxcodes.get(i));
//                                DataBaseControl.addUpRelation(relationUpInfo);
//                            }
                            switch (abBean.getErrcode()) {
                                case 1:
                                    msg = "用户ID不存在\n";
                                    break;
                                case 2:
                                    msg = "产品ID不存在\n请确认产品信息正确再扫描";
                                    break;
                                case 3:
                                    msg = "产品包装比例无效\n请确认产品信息正确再扫描";
                                    break;
                                case 4:
                                    msg = "数码无效\n请确认产品信息正确再扫描";
                                    break;
                                case 5:
                                    msg = "盒码数量不足一个包装\n请确认产品信息正确再扫描";
                                    break;
                                case 6:
                                    msg = "盒码长度无效\n请确认产品信息正确再扫描";
                                    break;
                                case 7:
                                    msg = "箱码重复\n请确认产品信息正确再扫描";
                                    break;
                                case 8:
                                    msg = "盒码重复\n请确认产品信息正确再扫描";
                                    break;
                                default:
                                    break;
                            }
                            boxcodes.clear();
                            casecode = "";
                            bean.setBoxcodes(boxcodes);
                            bean.setBoxNum(boxcodes.size());
                            int a = caseTotalNum(DataBaseControl.getlist(bean.getPid(), bean.getBatch()));
                            bean.setNum(a);
                            int b = caseUpTotalNum(DataBaseControl.getUplist(bean.getPid(), bean.getBatch()));
                            bean.setUpnum(b);
                            postHandle(listener, 0);
                        }
                    }
                } catch (Exception e) {
                    casecode = string;
                    for (int i = 0; i < boxcodes.size(); i++) {
                        RelationUpInfo relationUpInfo = new RelationUpInfo(null, bean.getPid(), bean.getPname(), bean.getBatch(), casecode, boxcodes.get(i));
                        DataBaseControl.addUpRelation(relationUpInfo);
                    }
                    boxcodes.clear();
                    casecode = "";
                    msg = "网络连接异常,已保存本地";
                    bean.setBoxcodes(boxcodes);
                    bean.setBoxNum(boxcodes.size());
                    int a = caseTotalNum(DataBaseControl.getlist(bean.getPid(), bean.getBatch()));
                    bean.setNum(a);
                    int b = caseUpTotalNum(DataBaseControl.getUplist(bean.getPid(), bean.getBatch()));
                    bean.setUpnum(b);
                    postHandle(listener, 0);
                }
            }
        }).start();
    }

    @Override
    public void deleteBox(String string, AbScanfBean abScanfBean, final CallBack listener) {
        try {
            bean = abScanfBean;
            if (boxcodeJudge(string)) {
                msg = "盒码长度不符";
                postHandle(listener, -1);
                return;
            }
            if (!boxcodes.contains(string)) {
                msg = "当前箱未包含此盒码";
                postHandle(listener, -1);
            } else {
                msg = "删除盒码成功";
                boxcodes.remove(string);
                bean.setBoxNum(boxcodes.size());
                postHandle(listener, 0);
            }
        } catch (Exception e) {
            msg = "数据处理异常";
            postHandle(listener, -1);
        }
    }

    @Override
    public void addCode(String string, AbScanfBean abScanfBean, final CallBack listener) {
        if (Integer.parseInt(abScanfBean.getCaseBoxNums()) == abScanfBean.getBoxNum()) {
            addCase(string, abScanfBean, listener);
        } else {
            addBox(string, abScanfBean, listener);
        }
    }

    private boolean boxcodeJudge(String code) {
        int a = HWApp.sSharedPreferences.getInt(Util.boxmixlen, 0);
        int b = HWApp.sSharedPreferences.getInt(Util.boxmaxlen, 0);
        if (code.length() >= a && code.length() <= b) {
            return false;
        } else {
            return true;
        }
    }

    private boolean casecodeJudge(String code) {
        int a = HWApp.sSharedPreferences.getInt(Util.casemixlen, 0);
        int b = HWApp.sSharedPreferences.getInt(Util.casemaxlen, 0);
        if (code.length() >= a && code.length() <= b) {
            return false;
        } else {
            return true;
        }
    }

    private boolean caseWl(String code) {
        try {
            ProductInfo productInfo = DataBaseControl.searchUnPid(bean.getPid());
            if (productInfo.getOtherCode().equals(code.substring(0, 2))) {
                return false;
            } else {
                return true;
            }
        }
        catch (Exception e)
        {
            return true;
        }
    }

    private String formatCaseBox() {
        String res = "";
        res = casecode + ":";
        for (int i = 0; i < boxcodes.size(); i++) {
            if (i == boxcodes.size() - 1) {
                res = res + boxcodes.get(i);
                break;
            } else {
                res = res + boxcodes.get(i) + ",";
            }
        }
        return res;
    }

    private String commitCode(final CallBack listener) {
        String res = "";
        try {
            String uurl = HWApp.sSharedPreferences.getString(Util.addk, "") + Util.urlsuffix +
                    "?action=UpdateCodes&cid=" +
                    HWApp.sSharedPreferences.getString(Util.cidk, "") +
                    "&userID=" + HWApp.sSharedPreferences.getInt(Util.userID, 0) +
                    "&productID=" + bean.getPid() +
                    "&batch=" + bean.getBatch() +
                    "&codes=" + formatCaseBox();
            Request request = new Request.Builder().url(uurl
            ).build();
            Log.e(tag, uurl);
            Response response = client.newCall(request).execute();
            res = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return res;
        }
    }


    private int caseTotalNum(List<RelationInfo> list) {
        int num = 0;
        String str = "";
        for (int i = 0; i < list.size(); i++) {
            if (!str.equals(list.get(i).getCasecode())) {
                num++;
                str = list.get(i).getCasecode();
            }
        }
        return num;
    }

    private int caseUpTotalNum(List<RelationUpInfo> list) {
        int num = 0;
        String str = "";
        for (int i = 0; i < list.size(); i++) {
            if (!str.equals(list.get(i).getCasecode())) {
                num++;
                str = list.get(i).getCasecode();
            }
        }
        return num;
    }
}

